<?php

namespace app\channel\controller\sys_admin;
use think\facade\Cache;
use think\Db;

use app\AdminController;

use app\channel\model\ProxyUsersModel;
use app\channel\model\ProxyLevelModel;
use app\channel\model\ProxyUsersSuperiorModel;
use app\channel\model\ProxyWarrantLogModel;
use app\channel\model\TeamModel;
use app\channel\model\LogSysModel;
use app\channel\model\ProxyUserRegionModel;
use app\channel\model\StockModel;
use app\member\model\UsersModel;
use app\member\model\UserAddressModel;
use app\mainadmin\model\RegionModel;
/**
 * 代理管理
 * Class Index
 * @package app\store\controller
 */
class Users extends AdminController
{
    /*------------------------------------------------------ */
    //-- 优先执行
    /*------------------------------------------------------ */
    public function initialize()
    {
        parent::initialize();
        $this->Model = new ProxyUsersModel();
    }
    /*------------------------------------------------------ */
    //-- 首页
    /*------------------------------------------------------ */
    public function index()
    {
        $this->assign("start_date", date('Y/m/01', strtotime("-2 year")));
        $this->assign("end_date", date('Y/m/d'));
        $this->getList(true);
        $this->assign('show_add',1);
        return $this->fetch('sys_admin/users/index');
    }

    /*------------------------------------------------------ */
    //-- 获取列表
    //-- $runData boolean 是否返回模板
    /*------------------------------------------------------ */
    public function getList($runData = false,$listType='all')
    {
        $this->assign('listType',$listType);
        $this->assign("statusArr", $this->Model->statusArr);
        $ProxyLevelModel = new ProxyLevelModel();
        $this->assign("proxyLevel", $ProxyLevelModel->getList());
        $this->search['keyword'] = input('keyword','','trim');
        $this->search['proxy_id'] = input('proxy_id','0','intval');
        $sort_by = input("sort_by", 'DESC', 'trim');
        $order_by = 'u.user_id';
        $url = 'info';
        $where = [];
        if ($listType == 'waitCheck'){
            $where[] = 'pu.join_condition = 1';
            $where[] = 'pu.status = 0';
            $url = 'waitCheckInfo';
        }elseif($listType == 'waitCheckIdCard'){
            $where[] = 'u.check_id_card = 2';
            $url = 'waitCheckIdCardInfo';
        }
        $this->assign('url',$url);
        if ($this->search['proxy_id'] > 0){
            $where[] = "pu.proxy_id = {$this->search['proxy_id']}";
        }
        $this->search['status'] = input('status','-1','intval');
        if ($this->search['status'] >= 0){
            $where[] = "pu.status = {$this->search['status']}";
        }

        $this->search['time_type'] = input('time_type','','trim');
        if (empty($this->search['keyword']) == false) {
            unset($this->search['time_type']);//关键字搜索取消时间限制
            if (is_numeric($this->search['keyword'])) {
                $where[] = " u.user_id = '" . ($this->search['keyword']) . "' or u.mobile like '" . $this->search['keyword'] . "%'";
            } else {
                $where[] = " ( u.real_name like '" . $this->search['keyword'] . "%' )";
            }
        }


        if (empty($this->search['time_type']) == false){
            $reportrange = input('reportrange','','trim');
            $dtime = explode('-', $reportrange);
            $dtime[0] = strtotime($dtime[0]);
            $dtime[1] = strtotime($dtime[1]) + 86399;
            switch ($this->search['time_type']) {
                case 'reg_time':
                    $where[] = ' pu.reg_time between ' . $dtime[0]  . ' AND ' . $dtime[1];
                    break;
                case 'login_time':
                    $where[] = ' pu.login_time between ' . $dtime[0]  . ' AND ' .$dtime[1];
                    break;
                case 'check_time':
                    $where[] = ' pu.check_time between ' . $dtime[0]  . ' AND ' .$dtime[1];
                    break;
                default:
                    break;
            }
        }

        $viewObj = $this->Model->alias('pu')->join("users u", 'pu.user_id=u.user_id', 'left')->where(join(' AND ', $where))->field('u.mobile,u.real_name,pu.*')->order($order_by . ' ' . $sort_by);

        $data = $this->getPageList($this->Model, $viewObj);
        $data['order_by'] = $order_by;
        $data['sort_by'] = $sort_by;
        $this->assign("data", $data);
        $this->assign("search",$this->search);
        if ($runData == false) {
            $data['content'] = $this->fetch('sys_admin/users/list')->getContent();
            return $this->success('', '', $data);
        }
        return true;
    }
    /*------------------------------------------------------ */
    //-- 注册待审
    /*------------------------------------------------------ */
    public function waitCheck()
    {
        $this->assign('show_add',0);
        $this->getList(true,'waitCheck');
        return $this->fetch('sys_admin/users/index');
    }
    /*------------------------------------------------------ */
    //-- 注册待审详情
    /*------------------------------------------------------ */
    public function waitCheckInfo()
    {
        return $this->info();
    }

    /*------------------------------------------------------ */
    //-- 实名待审
    /*------------------------------------------------------ */
    public function waitCheckIdCard()
    {
        $this->assign('show_add',0);
        $this->getList(true,'waitCheckIdCard');
        return $this->fetch('sys_admin/users/index');
    }
    /*------------------------------------------------------ */
    //-- 注实名待审详情
    /*------------------------------------------------------ */
    public function waitCheckIdCardInfo()
    {
        return $this->info();
    }
    /*------------------------------------------------------ */
    //-- 会员管理
    /*------------------------------------------------------ */
    public function info()
    {
        $user_id = input('user_id/d');
        if ($user_id < 1) return $this->error('获取用户ID传值失败！');
        $row = $this->Model->info($user_id);
        if (empty($row)) return $this->error('用户不存在！');
        $row['user_address'] = (new UserAddressModel)->where('user_id', $user_id)->select()->toArray();
        $this->assign('row', $row);
        $this->assign("proxyLevel", (new ProxyLevelModel)->getList());
        $this->assign("teamCount",(new TeamModel)->teamAllCount($user_id));
        $this->assign('statusArr',$this->Model->statusArr);
        $this->assign('regionProxy',$this->Model->regionProxy);
        $warrantLog = (new ProxyWarrantLogModel)->where('user_id', $user_id)->order('log_id DESC')->select()->toArray();
        $this->assign('warrantLog',$warrantLog);
        $this->assign('checkIDCardStatus',UsersModel::$checkIDCardStatus);
        $this->assign('isTeamTree',0);
        $stockTotal = (new StockModel)->where('user_id',$user_id)->field('purchase_type,sum(goods_number) as StockTotal')->group('purchase_type')->select()->toArray();
        $stockStat['cloudStockTotal'] = 0;
        $stockStat['entityStockTotal'] = 0;
        foreach ($stockTotal as $stock){
            if ($stock['purchase_type'] == 1){
                $stockStat['cloudStockTotal'] = $stock['StockTotal'];
            }else{
                $stockStat['entityStockTotal'] = $stock['StockTotal'];
            }
        }
        $this->assign('stockStat', $stockStat);
        return $this->fetch('sys_admin/users/info');
    }

    /*------------------------------------------------------ */
    //-- 上级名单
    /*------------------------------------------------------ */
    public function getSuperiorList()
    {
        $user_id = input('user_id', 0, 'intval');
        $result['code'] = 1;
        $result['list'] = $this->Model->getSuperiorList($user_id);
        return $this->ajaxReturn($result);
    }
    /*------------------------------------------------------ */
    //-- 修改所属上级
    /*------------------------------------------------------ */
    public function editSuperior()
    {
        $user_id = input('user_id', 0, 'intval');
        $userInfo = $this->Model->info($user_id);

        if ($this->request->isPost()) {
            $mkey = 'evalEditProxySuperior';
            $cache = Cache::get($mkey);
            if (empty($cache) == false){
                return $this->error('当前正在有人操作调整，请稍后再操作.');
            }
            Cache::get($mkey,true,60);
            $ProxyUsersSuperiorModel = new ProxyUsersSuperiorModel();
            $setTopUser = input('setTopUser', 0, 'intval');

            if ($setTopUser == 1){
                $select_user_id = 0;
                if ($select_user_id == $userInfo['pid']){
                    return $this->error('当前选择与当前代理上级一致，请核实.');
                }
            }else{
                $select_user_id = input('select_user', 0, 'intval');
                if ($select_user_id < 1){
                    return $this->error('请选择需要修改的上级.');
                }
                if ($select_user_id == $userInfo['pid']){
                    return $this->error('当前选择与当前代理上级一致，请核实.');
                }
                if ($select_user_id == $userInfo['user_id']){
                    return $this->error('不能选择自己作为自己的上级.');
                }
                $where[] = ['user_id','=',$select_user_id];
                $where[] = ['','exp',Db::raw("FIND_IN_SET('".$user_id."',superior)")];
                $count = $ProxyUsersSuperiorModel->where($where)->count();
                if ($count > 0){
                    return $this->error('不能选择自己的下级作为上级.');
                }
            }
            Db::startTrans();//启动事务
            $log = '调整代理所属上级，原所属上级ID：'.$userInfo['pid'];
            $ProxyLevelList = (new ProxyLevelModel)->getList();
            $_supply_uid = $this->Model->getSupplyUid($user_id,$userInfo['proxy_id'],$ProxyLevelList,$select_user_id);
            if ($_supply_uid != $userInfo['supply_uid']){
                $upData['supply_uid'] = $_supply_uid;
                $log .= '，供货上级ID调整为：'.$_supply_uid;
            }else{
                $log .= '，供货上级不调整.';
            }
            $upData['pid'] = $select_user_id;
            $res = $this->Model->upInfo($user_id,$upData);

            if ($res < 1){
                Db::rollback();
                return $this->error('修改代理所属上级失败.');
            }

            //会员上级汇总处理end
            $res = $ProxyUsersSuperiorModel->treat($user_id, $select_user_id, true);//重新绑定当前用户的关系链
            if ($res == false){
                Db::rollback();
                return $this->error('绑定当前代理关系链失败.');
            }
            //重置下级供货关系链
            $res = $this->Model->resetSupplyBind($user_id,$this);
            if ($res !== true) {
                Db::rollback();
                return $this->error($res);
            }
            Db::commit();//事务，提交
            Cache::rm($mkey);
            $this->_log($user_id, $log, 'channel');
            return $this->success('修改所属上级成功！', 'reload');
        }
        if ($userInfo['pid'] > 0){
            $userInfo['puser'] = $this->Model->info($userInfo['pid']);
        }
        $this->assign("row", $userInfo);
        return $this->fetch('sys_admin/users/edit_superior');
    }
    /*------------------------------------------------------ */
    //-- 查询代理
    /*------------------------------------------------------ */
    public function searchUser()
    {
        $keyword = input('keyword', '', 'trim');
        $where = " pu.user_id > 0 ";
        if (!empty($keyword)) {
            $where .= " AND  ( u.mobile LIKE '%" . $keyword . "%' OR u.user_id = '" . $keyword . "' OR u.real_name LIKE '%" . $keyword . "%' OR u.mobile LIKE '%" . $keyword . "%')";
        }
        $_list =  $this->Model->alias('pu')->join("users u", 'pu.user_id=u.user_id', 'left')->where($where)->field('u.user_id,u.mobile,u.real_name,pu.proxy_id')->limit(20)->select();
        $proxyLevel = (new ProxyLevelModel)->getList();
        foreach ($_list as $key => $row) {
            $row['proxy_name'] = $proxyLevel[$row['proxy_id']]['proxy_name'];
            $_list[$key] = $row;
        }
        $result['list'] = $_list;
        $result['code'] = 1;
        return $this->ajaxReturn($result);
    }
    /*------------------------------------------------------ */
    //-- 授权
    /*------------------------------------------------------ */
    public function warrant(){
        $user_id = input('user_id','0','intval');
        $userInfo = $this->Model->info($user_id);
        if (empty($userInfo)){
            return $this->error('用户不存在.');
        }
        $proxyLevel = (new ProxyLevelModel)->getList();
        $statusArr = $this->Model->statusArr;
        if ($this->request->isPost()) {
            $status = input('status',0,'intval');
            $check_remark = input('check_remark','','trim');
            if ($status == 1){//授权层级
                $this->warrant_end_time = input('warrant_end_time','','trim');
                if (empty($this->warrant_end_time)){
                    return $this->error('请选择授权结束时间.');
                }
                $proxy_id = input('proxy_id',0,'trim');
                if ($proxy_id < 1){
                    return $this->error('请选择授代理层级.');
                }
                $res = $this->Model->upgrade($user_id,$proxy_id,'后台授权',$this);
                if ($res !== true){
                    return $this->error($res);
                }
                return $this->success('操作成功.');
            }

            if ($status > 1){
                if (empty($check_remark)){
                    return $this->error('须填写操作备注.');
                }
                $upArr['check_remark'] = $check_remark;
            }
            $upArr['status'] = $status;
            if ($userInfo['status'] == 0){
                $upArr['check_time'] = time();
            }
            $res = $this->Model->upInfo($user_id,$upArr);
            if ($res < 1){
                return $this->error('更新授权失败，请重试.');
            }
            $log = '授权管理';
            if ($status != $userInfo['status']){
                 $log .= '，代理状态更改-'.$statusArr[$status];
            }
            if (empty($check_remark) == false){
                $log .= '，'.$check_remark;
            }
            $this->_log($user_id, $log, 'channel');

            return $this->success('操作成功.');
        }
        $this->assign('warrant_end_time',strtotime("+1 year"));
        $this->assign('proxyLevel',$proxyLevel);
        $this->assign('statusArr',$statusArr);
        $this->assign('userInfo',$userInfo);
        return $this->fetch('sys_admin/users/warrant');
    }
    /*------------------------------------------------------ */
    //-- 区域代理授权
    /*------------------------------------------------------ */
    public function regionProxy(){
        $user_id = input('user_id','0','intval');
        $userInfo = $this->Model->info($user_id);
        if (empty($userInfo)){
            return $this->error('用户不存在.');
        }
        $regionProxy = $this->Model->regionProxy;
        $ProxyUserRegionModel = new ProxyUserRegionModel();
        $RegionModel = new RegionModel();
        if ($this->request->isPost()) {
            $region_proxy = input('region_proxy','0','intval');
            $proxy_region_id = input('proxy_region_id');
            if ($region_proxy > 0 && empty($proxy_region_id)){
                return $this->error('请设置代理区域.');
            }
            Db::startTrans();//事务启动
            $log = '区域代理授权管理：设为：'.$regionProxy[$region_proxy];
            $count = $ProxyUserRegionModel->where('user_id',$user_id)->count();
            if ($count > 0){//存在内容，执行清理
                $ProxyUserRegionModel->where('user_id',$user_id)->delete();
            }
            $regionNames = [];
            if ($region_proxy > 0){//设为区域代理
                foreach ($proxy_region_id as $region_id){
                    $inData['region_id'] = $region_id;
                    $inData['user_id'] = $user_id;
                    $regionName = $RegionModel->where('id',$region_id)->value('merger_name');
                    //检查区域是否已授权其它代理
                    $count = $ProxyUserRegionModel->where('region_id',$region_id)->count();
                    if ($count > 0){
                        Db::rollback();//回滚
                        return $this->error($regionName.'已授权其它代理，不能重复授权，请核实.');
                    }
                    $regionNames[] = $regionName;
                    $res = $ProxyUserRegionModel->create($inData);
                    if ($res->region_id < 1){
                        Db::rollback();//回滚
                        return $this->error('保存代理区失败，请重试.');
                    }
                }
                $log .= '，代理区域：'.join('|',$regionNames);
            }

            $upArr['region_proxy'] = $region_proxy;
            $res = $this->Model->upInfo($user_id,$upArr);
            if ($res < 1){
                Db::rollback();//回滚
                return $this->error('更新区域代理授权失败，请重试.');
            }
            Db::commit();//事务提交
            $this->_log($user_id, $log, 'channel');
            return $this->success('操作成功.');
        }
        $regionList = [];
        if ($userInfo['region_proxy'] > 0){
            $region_ids = $ProxyUserRegionModel->where('user_id',$user_id)->column('region_id');
            $where = [];
            $where[] = ['id','IN',$region_ids];
            $regionList = $RegionModel->where($where)->field('id,merger_name')->select()->toArray();
        }
        $this->assign('regionList',$regionList);
        $this->assign('regionProxy',$regionProxy);
        $this->assign('userInfo',$userInfo);
        return $this->fetch('sys_admin/users/region_proxy');
    }
    /*------------------------------------------------------ */
    //-- 实名审核
    /*------------------------------------------------------ */
    public function checkIdCard()
    {
        $user_id = input('user_id', 0, 'intval');
        $userInfo = $this->Model->info($user_id);
        $UsersModel = new UsersModel();
        $checkIDCardStatus = $UsersModel::$checkIDCardStatus;
        if ($this->request->isPost()) {
            $check_id_card = input('check_id_card',0,'intval');
            $UsersModel->upInfo($user_id,['check_id_card'=>$check_id_card]);
            $this->_log($user_id, '实名认证：'.$checkIDCardStatus[$check_id_card], 'channel');
            $this->Model->cleanMemcache($user_id);
            return $this->success('授权成功.');
        }
        $this->assign('checkIDCardStatus',$checkIDCardStatus);
        $this->assign('userInfo',$userInfo);
        return $this->fetch('sys_admin/users/check_id_card');
    }
    /*------------------------------------------------------ */
    //-- 获取用户操作日志
    /*------------------------------------------------------ */
    public function getOptLogList()
    {
        $user_id = input('user_id', 0, 'intval');
        if ($user_id < 1){
            return $this->error('代理ID不能为空');
        }
        $logs = (new LogSysModel)->where('edit_id',$user_id)->order('log_id DESC')->select()->toArray();
        foreach ($logs as $key=>$log){
            $log['admin_info'] = $log['user_id'].'-'.adminInfo($log['user_id']);
            $log['log_time'] = dateTpl($log['log_time']);
            $logs[$key] = $log;
        }
        $data['list'] = $logs;
        return $this->success('ok','',$data);
    }
    /*------------------------------------------------------ */
    //-- 平台邀请代理
    /*------------------------------------------------------ */
    public function share(){
        $ProxyLevelModel = new ProxyLevelModel();
        $this->assign("proxyLevel", $ProxyLevelModel->getList());
        return $this->fetch();
    }
    /*------------------------------------------------------ */
    //-- 平台邀请代理
    /*------------------------------------------------------ */
    public function getShareQrcode(){
        $proxy_id = input('proxy_id',0,'intval');
        $share_type = input('share_type','','trim');
        if ($share_type == 'H5'){
            $file_path = config('config._upload_') . 'snap_file/';
            $data['shareUrl'] = settings("channel_web_url") . '/pagesB/channel/passport/register?share_token=' . settings("channel_token") . '&proxy_id=' . $proxy_id;
            $file = $file_path .'channel_share_'.md5($data['shareUrl']) . '.png';
            if (file_exists($file) == false) {
                include EXTEND_PATH . 'phpqrcode/phpqrcode.php';//引入PHP QR库文件
                $QRcode = new \phpqrcode\QRcode();
                makeDir($file_path);
                $QRcode::png($data['shareUrl'], $file, "L", 10, 1, 2, true);
            }
            $data['file'] = trim($file, '.');
            return $this->success('ok','',$data);
        }
        return $this->error();
    }

}
